package com.zhan.drugStore.controller;

import com.zhan.drugStore.config.MinioConfig;
import com.zhan.drugStore.util.MinioUtil;
import com.zhan.drugStore.util.ResponseBase;
import com.zhan.drugStore.util.ResponseBean;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;


@Slf4j
@RestController
@RequestMapping(value = "/file")
public class FileController extends SuperController {
    @Resource
    private MinioUtil minioUtil;
    @Resource
    private MinioConfig prop;

    @ApiOperation(value = "文件上传返回url")
    @PostMapping("/upload")
    public ResponseBean<String> upload(@RequestParam("file") MultipartFile file) {
        String objectName = minioUtil.upload(file);
        return super.resultSuccess(prop.getEndpoint() + "/" + prop.getBucketName() + "/" + objectName);
    }

    @ApiOperation(value = "文件下载")
    @GetMapping("/download")
    public ResponseBase download(@RequestParam("fileName") String fileName, HttpServletResponse res) {
        minioUtil.download(fileName, res);
        return super.resultSuccess();
    }

    @ApiOperation(value = "删除文件", notes = "根据url地址删除文件")
    @GetMapping("/delete")
    public ResponseBase remove(@RequestParam String url) {
        String objName = url.substring(url.lastIndexOf(prop.getBucketName() + "/") + prop.getBucketName().length() + 1);
        minioUtil.remove(objName);
        return super.resultSuccess();
    }
}
